package app;

import com.alibaba.fastjson.JSON;
import domain.Access;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import udf.MySqlSinkT3;
import utils.MySqlTableUtils;
import utils.MySqlUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * Create by zhh on 2022/9/9.
 * 按照操作系统维度进行新老用户的统计分析（）
 */
public class OsUserAppV1 {
    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        SingleOutputStreamOperator<Access> cleanData = env.readTextFile("data/access.json").map(new MapFunction<String, Access>() {
            @Override
            public Access map(String s) throws Exception {
                //TODO... json==>Access
                try {
                    return JSON.parseObject(s, Access.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
        })
                .filter(x -> x != null)
                .filter(new FilterFunction<Access>() {
                    @Override
                    //过滤启动的用户
                    public boolean filter(Access access) throws Exception {
                        return "startup".equals(access.event);
                    }
                });
        //TODO... 操作系统维度  新老用户 ==>wc  (操作系统，新老用户，新老用户数)
        //(Android,1,28)  (Android,0,18)  (iOS,1,39) (iOS,0,15) 1是新用户，0是老用户
        SingleOutputStreamOperator<Tuple3<String, Integer, Integer>> result = cleanData.map(new MapFunction<Access, Tuple3<String, Integer, Integer>>() {
            @Override
            //map成（操作系统，新老用户，1）
            public Tuple3<String, Integer, Integer> map(Access access) throws Exception {
                return Tuple3.of(access.os, access.nu, 1);
            }
        }).keyBy(new KeySelector<Tuple3<String, Integer, Integer>, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> getKey(Tuple3<String, Integer, Integer> value) throws Exception {
                return Tuple2.of(value.f0, value.f1);
            }
        }).sum(2);

        result.addSink(new MySqlSinkT3());//自定义Sink，但要在utils包中的MySqlTableUtils中修改要Sink的表名和列名

        env.execute();
    }

}